package org.example.io.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.example.io.protocol.Packet;
import org.example.io.protocol.packet.*;

@Slf4j
public class ServerLoginHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 把消息送下一步
        ByteBuf byteBuf = (ByteBuf) msg;
        Packet packet = PacketCodec.INSTANCE.decode(byteBuf);
        if (packet instanceof LoginRequestPacket) {
            LoginRequestPacket requestPacket = (LoginRequestPacket) packet;
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
            if (validLogin(requestPacket.getUserName(), requestPacket.getPassword())) {
                loginResponsePacket.setSuccess(true);
                log.info("{}登录成功", requestPacket.getUserName());
            } else {
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setMessage("用户名密码不正确");
                log.info("{}登录失败", requestPacket.getUserName());
            }
            ByteBuf resByte = PacketCodec.INSTANCE.encode(loginResponsePacket);
            ctx.writeAndFlush(resByte);
        } else if (packet instanceof MessageRequestPacket) {
            MessageRequestPacket requestPacket = (MessageRequestPacket) packet;
            String message = requestPacket.getMessage();
            log.info("收到消息：{}", message);

            MessageResponsePacket resPacket = new MessageResponsePacket();
            resPacket.setMessage("from server : " + message);
            ByteBuf resByte = PacketCodec.INSTANCE.encode(resPacket);
            ctx.writeAndFlush(resByte);
        }
    }

    public boolean validLogin(String username, String password) {
        return true;
    }
}
